use std::fs::File;
use std::io;
use std::io::Read;
use rand::{distributions::Uniform, Rng, thread_rng};
use std::time::{Duration, Instant};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();

    read_file_one().unwrap();
    File::open("hello.txt")?.read_to_string(&mut s)?;

    Ok(s)
}

fn read_file_one() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("1.txt")?.read_to_string(&mut s)?;
    File::open("2.txt")?.read_to_string(&mut s)?;
    File::open("3.txt")?.read_to_string(&mut s)?;
    File::open("4.txt")?.read_to_string(&mut s)?;
    File::open("5.txt")?.read_to_string(&mut s)?;
    File::open("6.txt")?.read_to_string(&mut s)?;
    Ok(s)
}



fn first(arr: &[i32]) -> Option<&i32> {
   let v = arr.get(0)?;
   Some(v)
}

fn rand_str(length: usize, str: &str) -> String {
    let str_chars: Vec<char> = str.chars().collect();
    let str_len = str_chars.len();
    let range = Uniform::from(0..str_len);

    let mut rng = rand::thread_rng();
    let mut res = String::new();

    for _ in 0..length {
        let idx = rng.sample(&range);
        res.push(str_chars[idx]);
    }

    res
}

// fn rand_str(len: usize, rang: &str) -> String {
//     let rand_max = rang.chars().count() - 1;
//     let mut res = String::new();
//     let mut rng = thread_rng();

//     for _ in 0..len {
//         res.push(rang.chars().nth(rng.gen_range(0..=rand_max)).unwrap());
//     }

//     res
// }

#[test]
fn test_rand_str() {
    let case_num = 500_500;
    let mut cases = Vec::with_capacity(case_num);
    let rand_range = "abcdefghijklmnopqrstuvwxyz0123456789";
    let start = Instant::now();

    for _ in 0..case_num {
        cases.push(thread_rng().gen_range(0..999));
    }
    let case_end = Instant::now();
    println!("case cost {:?}", case_end.duration_since(start));

    for c in cases.iter() {
        rand_str(*c as usize, rand_range);
    }
    let test_end = Instant::now();
    println!("func cost {:?}", test_end.duration_since(case_end));
}


fn main() {
    let random_string = rand_str(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
    println!("Random String: {}", random_string);
}
